<template>
  <div class="app-container v-flex">
    <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm" />
    <div ref="main" class="v-flex-elastic">
      <el-table
        v-if="height>0"
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        border
        :height="height"
        tooltip-effect="dark"
        style="width: 100%">
        <el-table-column label="序号" align="center" type="index" width="50" />
        <el-table-column prop="deptName" label="部门" />
        <el-table-column label="开始时间" :formatter="row => parseTime(row.startTime, '{y}-{m}-{d}')" />
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="130"
          class-name="small-padding fixed-width">
          <template slot-scope="{row ,$index}">
            <el-button
              v-permission-button="publicConfig['ITPS-VIEW']"
              class="el-icon-defined"
              size="mini"
              icon="el-icon-view"
              @click="view(row)" />
            <el-button
              v-permission-button="publicConfig['ITPS-UPDATE']"
              class="el-icon-defined"
              size="mini"
              icon="el-icon-edit"
              @click="updateForm(row,$index)" />
            <el-button
              v-permission-button="publicConfig['ITPS-DELETE']"
              class="el-icon-defined"
              size="mini"
              icon="el-icon-delete"
              @click="deleteData(row,$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <base-dialog
      class="safety-days-dialog"
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :loading="dialog.loading"
      :disabled="dialog.disabled"
      @open="beforeOpenDialog"
      @updateData="updateData">
      <el-form
        ref="dataForm"
        :rules="dialog.rules"
        :model="dialog.form"
        :disabled="dialog.disabled"
        label-width="120px">
        <el-form-item label="部门" prop="deptId">
          <select-tree
            v-model="dialog.form.deptId"
            node-click
            :options="depts"
            :props="{parent: 'parentId',value: 'id',label: 'label',children: 'children'}"
            @nodeClick="changeDept"
            @clear="clearDept" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="dialog.form.startTime" value-format="timestamp" />
        </el-form-item>
      </el-form>
    </base-dialog>
  </div>
</template>
<script>
import {
  getListPage,
  updateData,
  deleteData
} from '@/api/dsc/system/safety-days'
import { getListAllTree } from '@/api/dsc/system/department'
import { parseTime } from '@/utils'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscSafetyDays',
  mixins: [tableMixin],
  data() {
    return {
      listQuery: {},
      filterData: {},
      height: 0,
      listLoading: true,
      tableData: [],
      total: 0,
      dialog: {
        title: '',
        visible: false,
        disabled: false,
        loading: false,
        initForm: {
          status: 1,
          delFlag: 0
        },
        form: {},
        rules: {
          deptId: { required: true, message: '请选择', trigger: 'change' },
          startTime: { required: true, message: '请选择', trigger: 'change' }
        }
      },
      currentRow: [],
      depts: [],
      parseTime: parseTime
    }
  },
  created() {
    this.getList()
    this.getListPage()
  },
  methods: {
    getList() {
      getListAllTree().then(response => {
        this.depts = response.data
      })
    },
    getListPage() {
      this.listLoading = true
      getListPage(this.listQuery)
        .then(response => {
          this.tableData = response.data
          this.listLoading = false
        })
        .catch(_ => {
          this.listLoading = false
        })
    },
    search() {
      this.getListPage()
    },
    /** 查看 */
    view(row) {
      this.currentRow = [row]
      const dialog = {
        title: '查看',
        visible: true,
        disabled: true,
        loading: false,
        form: row
      }
      this.dialog = Object.assign(this.dialog, dialog)
    },
    /** 添加 */
    addForm() {
      const dialog = {
        title: '添加',
        visible: true,
        disabled: false,
        loading: false,
        form: JSON.parse(JSON.stringify(this.dialog.initForm))
      }
      this.dialog = Object.assign(this.dialog, dialog)
    },
    /** 编辑 */
    updateForm(row, index) {
      this.currentRow = [row]
      const dialog = {
        title: '编辑',
        visible: true,
        disabled: false,
        loading: false,
        form: JSON.parse(JSON.stringify(row))
      }
      this.dialog = Object.assign(this.dialog, dialog)
    },
    /** 添加或编辑接口 */
    updateData() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.dialog.loading = true
          updateData(this.dialog.form)
            .then(response => {
              this.dialog.visible = false
              this.dialog.loading = false
              this.currentRow = [response.data]
              if (this.dialog.title === '添加') {
                this.tableData.unshift(this.currentRow[0])
              } else {
                const index = this.tableData.findIndex(
                  item => item.id === this.currentRow[0].id
                )
                this.tableData.splice(index, 1, JSON.parse(JSON.stringify(this.currentRow[0])))
                this.$forceUpdate()
              }
              this.notifiySuccess('保存成功')
            })
            .catch(_ => {
              this.dialog.loading = false
            })
        }
      })
    },
    deleteData(row, index) {
      this.confirmBox('确定删除?')
        .then(() => {
          deleteData(row.id).then(response => {
            this.notifiySuccess('删除成功!')
            this.tableData.splice(index, 1)
          })
        })
        .catch(() => {})
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    changeDept(vm, node) {
      this.dialog.form = Object.assign({}, this.dialog.form, {
        deptName: node.label,
        deptId: node.id,
        deptTypeCodes: node.obj.deptTypeNames.map(item => item.deptTypeCode)
      })
    },
    clearDept() {
      this.dialog.form = Object.assign({}, this.dialog.form, {
        deptName: '',
        deptId: '',
        deptTypeCodes: []
      })
    }
  }
}
</script>
